# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import JsonResponse

# mysql
import pymysql
# http
import requests
# 调用系统shell命令
import os
from subprocess import call
# 线程
import _thread
import time
import threading

import hashlib
import json
from django.utils.encoding import smart_str

from django.views.decorators.csrf import csrf_exempt

from django.template.loader import render_to_string
from django.views.decorators.csrf import ensure_csrf_cookie
from lxml import etree
import urllib3
from django.core.cache import cache
import sys
# 第一种导入方式
# sys.path.append(r'D:\PycharmProjects\weiXin\project\utils')
# 这里使用的是第二种  在Python安装目录下的\Lib\site-packages文件夹中建立一个.pth文件，内容为自己写的库路径 D:\PycharmProjects\weiXin\project\utils
from Utils import Utils;


# csrf_exempt装饰器是取消Django的csrf标记的，毕竟微信不会有这种标记。这次认证通过之后，这个方法你注销了都行，除非你再次认证，不然不会再使用这个方法了。
@csrf_exempt
# 如果request提供，它必须是一个HttpRequest。然后，引擎必须将其以及模板中可用的CSRF令牌。
@ensure_csrf_cookie
def weixin(request):
    '''
    zhouzhongqing
    2017年12月10日12:42:55
    微信服务器配置验证
    param request:
    return: 返回 echostr
     '''
    if request.method == 'GET':
        # 下面这四个参数是在接入时，微信的服务器发送过来的参数
        signature = request.GET.get('signature', None);
        timestamp = request.GET.get('timestamp', None);
        nonce = request.GET.get('nonce', None);
        echostr = request.GET.get('echostr', None);
        # 这里的token需要自己设定，主要是和微信的服务器完成验证使用
        token = 'zit';
        # 把token，timestamp, nonce放在一个序列中，并且按字符排序
        hashlist = [token, timestamp, nonce];
        hashlist.sort();
        # 将上面的序列合成一个字符串
        hashstr = ''.join([s for s in hashlist]);
        # 通过python标准库中的sha1加密算法，处理上面的字符串，形成新的字符串。
        hashstr = hashlib.sha1(hashstr.encode(encoding='utf-8')).hexdigest();
        # 把我们生成的字符串和微信服务器发送过来的字符串比较，
        # 如果相同，就把服务器发过来的echostr字符串返回去
        if hashstr == signature:
            return HttpResponse(echostr);
        else:
            return HttpResponse("error");
    if request.method == "POST":
        # 将程序中字符输出到非 Unicode 环境（比如 HTTP 协议数据）时可以使用 smart_str 方法
        data = smart_str(request.body);
        # print("recv data  : ",data);
        # 将接收到数据字符串转成xml
        xml = etree.fromstring(data);
        # 从xml中读取我们需要的数据。注意这里使用了from接收的to，使用to接收了from，
        # 这是因为一会我们还要用这些数据来返回消息，这样一会使用看起来更符合逻辑关系
        fromUser = xml.find('ToUserName').text;
        toUser = xml.find('FromUserName').text;
        msgType = xml.find('MsgType').text
        # 这里获取当前时间的秒数，time.time()取得的数字是浮点数，所以有了下面的操作
        nowTime = str(int(time.time()));
        #weChatMenu(request);
        # 加载text.xml模板,参见render()调用render_to_string()并将结果馈送到 HttpResponse适合从视图返回的快捷方式 。
        if msgType == 'text':
            content = xml.find('Content').text
            rendered = render_to_string('weChat/text.xml',
                                        {'ToUserName': toUser, 'FromUserName': fromUser, 'CreateTime': nowTime,
                                         'Content': '您发送的消息:' + content});
            # print("send data : " , rendered);
            return HttpResponse(rendered);

'''
CREATE TABLE `video` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',
  `name` varchar(50) NOT NULL COMMENT '名称',
  `url` varchar(500) NOT NULL COMMENT '地址',
  `createTime` datetime NOT NULL COMMENT '创建时间',
  `updateTime` datetime DEFAULT NULL COMMENT '更新时间',
  `userId` int(11) NOT NULL COMMENT '管理员id',
  `status` int(1) NOT NULL COMMENT '状态 0 - 锁定 1 - 启用',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8 COMMENT='视频';
'''

'''
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (1, '视频1', 'http://vip.jlsprh.com/index.php?url=', '2017-12-24 13:05:32', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (2, 'fastflv', 'http://api.fastflv.cc/jiexi/?url=', '2017-12-24 13:17:34', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (3, '自用的解析接口 CDN加速 优酷/爱奇艺/各大网站VIP视频解析 无广告', 'http://cdn.yangju.vip/k/player.php?v=', '2017-12-24 13:18:12', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (4, '自用视频解析稳定才是最重要的，维护超级快', 'http://api.avtv.fun/vip/?url=', '2017-12-24 18:51:09', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (5, '免费解析接口，稳定+专人值守，做视频站的不二选择', 'http://www.aktv.men/?url=', '2017-12-24 18:51:47', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (6, '【已更新】看挺多人都在找无广告解析，我这边分享给大家一个，绝对无广告的高速解析。', 'http://www.kuzhuys.com/player/index.php?url=', '2017-12-24 18:52:44', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (7, '支持各大网站腾讯,爱奇艺,优酷,VIP等！PC+手机无广告', 'http://api.zuilingxian.com/jiexi.php?url=', '2017-12-24 18:53:26', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (8, '分享一个免费稳定解析支持优酷，腾讯等主流视频网站VIP普通视频解析', 'http://www.love-six.com/vip/?url=', '2017-12-24 18:53:51', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (9, '自用免费万能解析接口分享', 'http://j.chanchangou.com/vip/index.php?url=', '2017-12-24 19:06:56', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (10, '指尖云解析', 'http://api.zj0763.com/index.php?url= ', '2017-12-24 19:08:08', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (11, '警告！前方高能：一大波福利来袭，速度来拿！免费解析无广告，还不要钱！', 'http://www.ifree8.top/jiexi/jiexi.php?url=', '2017-12-24 19:09:41', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (12, '百域阁', 'http://api.baiyug.cn/vip/index.php?url=', '2017-12-24 19:23:24', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (13, 'http://api.baiyug.cn/vip/index.php?url=', 'http://api.baiyug.cn/vip/index.php?url=', '2018-01-15 22:48:08', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (14, 'http://jx.ejiafarm.com/dy.php?url=', 'http://jx.ejiafarm.com/dy.php?url=', '2018-01-15 22:48:30', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (15, 'http://www.vipjiexi.com/yun.php?url=', 'http://www.vipjiexi.com/yun.php?url=', '2018-01-15 22:48:45', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (16, 'http://api.1008net.com/v.php?url=', 'http://api.1008net.com/v.php?url=', '2018-01-15 22:49:29', NULL, 1, 1);
INSERT INTO `video`.`video`(`id`, `name`, `url`, `createTime`, `updateTime`, `userId`, `status`) VALUES (17, 'http://api.nepian.com/ckparse/?url=', 'http://api.nepian.com/ckparse/?url=', '2018-01-15 22:50:31', NULL, 1, 1);

'''

def videoAddr(request):
    conn = pymysql.connect(host=Utils.HOST, port=Utils.PORT, user=Utils.USER, passwd=Utils.PASSWD, db=Utils.DB,
                           charset=Utils.CHARSET)
    cur = conn.cursor();
    id = request.POST['id'];
    print("id :" , id)
    url = request.POST['url'];
    sql = "SELECT id,name,url FROM video where 1= 1  and status = '1' and id=" + id;
    print("---", sql);
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();
    result = {};
    for row in results:
        result["id"] = row[0];
        result["name"] = row[1];
        result["url"] = row[2] + url;
        # print(row,"：result");
        # print('result:', row);
        # print('result:', row[0]);
    cur.close()
    conn.close()
    return JsonResponse(result);


def videoList(request):
    conn = pymysql.connect(host=Utils.HOST, port=Utils.PORT, user=Utils.USER, passwd=Utils.PASSWD, db=Utils.DB,
                           charset=Utils.CHARSET)
    cur = conn.cursor();
    sql = "SELECT id,name FROM video WHERE  1=1 and status = '1' ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();
    jsonStr = [];
    for row in results:
        result = {};
        result["id"] = row[0];
        result["name"] = row[1];
        # print(row,"：result");
        # print('result:', row);
        # print('result:', row[0]);
        jsonStr.append(result);
    cur.close()
    conn.close()
    return JsonResponse(jsonStr, safe=False);


'''
zhouzhongqing
2017年12月14日23:28:27
微信菜单
'''


def weChatMenu(request):
    utils = Utils();
    print(utils.CGI_BIN_TOKEN.replace("APPID", utils.APPID).replace("APPSECRET", utils.APPSECRET));
    result = requests.get(utils.CGI_BIN_TOKEN.replace("APPID", utils.APPID).replace("APPSECRET", utils.APPSECRET));
    # print("token recv  ",result.text)
    jsonText = result.text;
    jsonText = json.loads(jsonText);
    accessToken = jsonText["access_token"];
    print("access_token -- ", accessToken);
    postData = render_to_string('static/weChat/menu.json');
    result = requests.post(utils.MENU_CREATE.replace("ACCESS_TOKEN", accessToken), data=postData);
    jsonText = result.text;
    print("recv menu : ", jsonText);
    return HttpResponse("");


def video(request):
    return render(request, "views/video.html")


def hello(request):
    a = Utils();
    b = Utils();
    print(a, b)
    print(a.CGI_BIN_TOKEN.replace("APPID", a.APPID).replace("APPSECRET", a.APPSECRET));

    return render(request, "hello.html")


def ui(request):
    # return HttpResponse("Hello world ! ")
    context = {}
    context['hello'] = 'Hello kengya World!'
    return render(request, 'jqueryUITest.html', context)


# 接收请求数据
def search(request):
    # request.encoding='utf-8'
    # if 'q' in request.GET:
    # message = '你搜索的内容为: ' + request.GET['q'].encode('utf-8')
    # else:
    #	message = '你提交了空表单'
    return HttpResponse('内容'.encode('utf-8') + request.GET['q'].encode('utf-8'))


# 接收POST请求数据
def search_post(request):
    ctx = {};
    if request.POST:
        ctx['rlt'] = '你输入的是' + request.POST['q']
    return render(request, "hello.html", ctx)


# 接收POST请求数据AJAX
def ajax_post(request):
    name_dict = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'};
   # jsonStr = [];
   # jsonStr.append(name_dict);
    '''
    conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='ecshop', charset='UTF8')
    cur = conn.cursor();
    # 新增
    #	cur.execute("insert into tab1(tab1_id,val) VALUES (3,3)");
    # 查询mysql版本	cur.execute("SELECT VERSION()");

    # SQL 查询语句
    sql = "SELECT * FROM tab1 ";
    cur.execute(sql);
    # 获取所有记录列表
    results = cur.fetchall();
    for row in results:
        # print(row,"：result");
        print('result:', row);
        print('result:', row[0]);
    cur.close()
    conn.close()
    '''
    # 执行系统shell命令
    # menu = os.system('dir');
    # print('menu:',menu);
    return_code = call("echo Hello World", shell=True);
    print('return_code:', return_code);
    #return JsonResponse(jsonStr);如果不是数组不用加safe=False
    #return JsonResponse(jsonStr,safe=False);
    return JsonResponse(name_dict);


def requests_test(request):
    # get请求
    #  result =  requests.get('http://localhost/tzshop/webService/Interfere.php');
    # POST请求
    result = requests.post('http://localhost/tzshop/webService/Interfere.php', data={'params': 'python3.5'});
    name_dict = {'twz': result.text};
    return JsonResponse(name_dict);


# 线程测试------例1
# 为线程定义一个函数
def print_time1(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s: %s" % (threadName, time.ctime(time.time())))


exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("开始线程：" + self.name)
        print_time(self.name, self.counter, 5)
        print("退出线程：" + self.name)


def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit();
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


# main方法入口
if __name__ == '__main__':
    # 网络请求测试
    '''result = requests.get('http://localhost/tzshop/webService/Interfere.php');
    print('得到的结果', result.text);'''
    print('开始执行');
# 命令执行
# print(call('java -version'));
# print(call('D:/Xshell 5/Xshell.exe'));
# 创建两个线程
# 创建两个线程
'''	try:
	   _thread.start_new_thread( print_time1, ("Thread-1", 2, ) )
	   _thread.start_new_thread( print_time1, ("Thread-2", 4, ) )
	except:
	   print ("Error: 无法启动线程")

	while 1:
	   pass'''
# 创建新线程
'''thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()
#join阻塞主线程
thread1.join()
thread2.join()
print ("退出主线程")
print('执行完成');
p = Parent()
p.setAttr(1000);
p.getAttr();'''
